<template>
    <div class="inventory-add-form">
        <div class="section">
            <h2 class="section-title">盘点基本信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="qty_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm" :disabled='isSavedPd'>
                <el-form-item label="盘点单号" prop="qty_code">
                    <el-input v-model="qty_order.qty_code" placeholder="不输入则自动获取编号" />
                </el-form-item>

                <div class="form-columns">
                    <!-- 左侧表单 -->
                    <div class="form-column">
                        <el-form-item label="盘点类型" prop="qty_type" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.qty_type" placeholder="请选择盘点类型">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>


                        <el-form-item label="盘点结束日期" prop="qty_end" style="margin-bottom: 30px;">
                            <el-date-picker v-model="qty_order.qty_end" type="datetime" placeholder="选择日期时间"
                                @change="validateEndDate" style="width: 100%;" />
                        </el-form-item>



                        <el-form-item label="盘点库区" prop="zone_code" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.zone_code" placeholder="请选择盘点仓库" @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>

                    </div>

                    <!-- 右侧表单 -->
                    <div class="form-column">

                        <el-form-item label="盘点开始日期" prop="qty_startdate" style="margin-bottom: 30px;;">
                            <el-date-picker v-model="qty_order.qty_startdate" type="datetime" placeholder="选择日期时间"
                                style="width: 98%; margin-left:7px;" />
                        </el-form-item>




                        <el-form-item label="盘点仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.warehouse_code" placeholder="请选择盘点仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">盘点产品明细</h2>
            <div class="product-actions">
                <el-button type="primary" @click="productAdd">添加产品</el-button>
                <el-button @click="productDel">移除选中</el-button>

            </div>

            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="stock_numder" label="当前库存" width="110" />
                <el-table-column prop="location_code" label="盘点库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            :disabled="isDisabledlocation" @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="盘点数量" width="100">
                    <template #default="scope">
                        <el-input :disabled='isSavedPd' v-model="scope.row.proddti_stockcnt" style="width: 75px"
                            :precision="2" :min="0" />
                    </template>
                </el-table-column>

                <el-table-column label="盘亏数量" width="100">
                    <template #default="scope">
                        <el-input v-model="scope.row.proddti_loss" style="width: 75px" :precision="2" :min="0"
                            :readonly="true" />
                    </template>
                </el-table-column>
                <el-table-column label="盘盈数量" width="100">
                    <template #default="scope">
                        <el-input v-model="scope.row.proddti_profit" style="width: 75px" :precision="2" :min="0"
                            :readonly="true" />
                    </template>
                </el-table-column>

                <el-table-column prop="pro_cost_price" label="成本价" width="108" />
                <el-table-column prop="pro_sale_price" label="销售价" width="100" />
                <el-table-column label="盘亏金额" width="120">
                    <template #default="scope">
                        <span>{{ (scope.row.proddti_loss * scope.row.pro_cost_price).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="盘盈金额" width="110">
                    <template #default="scope">
                        <span>{{ (scope.row.proddti_profit * scope.row.pro_sale_price).toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div class="summary-row">
                <span>合计</span>
                <div class="summary-values">
                    <span>盘亏总量：{{ total_loss_qty }}</span>
                    <span>盘盈总量：{{ total_profit_qty }}</span>
                    <span>盘亏总金额：{{ total_loss_price.toFixed(2) }}</span>
                    <span>盘盈总金额：{{ total_profit_price.toFixed(2) }}</span>
                </div>
            </div>
        </div>

        <div class="button-group">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div class="product-filter">
            <el-input v-model="productcode" placeholder="请输入货品编号/名称" style="width: 240px; margin-right: 20px;" />
            <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                    :value="item.dict_value" />
            </el-select>
            <el-button @click="productReset">重置</el-button>
            <el-button type="primary" @click="productSearch">查询</el-button>
        </div>

        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isProductSelectable" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="成本价" />
            <el-table-column property="pro_sale_price" label="销售价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>

        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 盘点类型
const options = ref([])
// 仓库列表
const warehouses = ref([]);

//库区列表
const Warhouse_zone=ref([]);

//库位列表
const Warehouse_location=ref([]);

// 当前用户
const userName = localStorage.getItem('userLName') || '管理员';

// 盘点单对象
let qtyAdd = {
    qty_type: "",         // 盘点类型
    qty_code: "",          // 盘点单号
    qty_clerk: userName,   // 盘点人proddti_correct
    qty_startdate: "",     // 盘点开始日期
    qty_end:"",            // 盘点结束日期
    warehouse_code: "",    // 仓库编码
    warehouse_name: "",    // 仓库名称
    zone_code: "",          //库区编码
    zone_name: "",           //库区名称
  
    del_flag: '0',         // 删除状态
    create_by: userName,   // 创建人
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 创建时间 
    proddti_correct: '0',  // 修正状态
    //判断是否入库--0未入库 1已入库,用来在其他入库单显示订单
    qty_store:'0',
    //判断是否出库--0未出库 1已出库,用来在其他出库单显示订单--盘亏
    qty_store_bhg:'0',
}

// 盘点单表单对象
const qty_order = reactive({ ...qtyAdd })

// 表单验证
const ruleFormRef = ref(null)
const rules = reactive({
    warehouse_code: [{ required: true, message: '请选择盘点仓库', trigger: 'change' }],
    qty_type: [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
    qty_startdate: [{ required: true, message: '请选择盘点开始日期', trigger: 'change' }],
    qty_end: [{ required: true, message: '请选择盘点结束日期', trigger: 'change' }],
    zone_code: [{ required: true, message: '请选择盘点库区', trigger: 'change' }]
});

// 产品相关状态
const dialogTableVisible = ref(false) // 控制添加产品模态框的显示/隐藏
const productData = ref([])          // 存储从API获取的产品列表数据
const currentPage = ref(1)           // 产品列表的当前页码
const pageSize = ref(5)              // 每页显示的产品数量
const pageCount = ref(0)             // 产品列表的总记录数

const productcode = ref("")          // 产品搜索关键字（名称/编号）
const dict_code = ref("0")           // 选中的计量单位ID（用于筛选）

const measureOptios = ref([])        // 存储计量单位选项列表
const multipleTableRef = ref(null);  // 产品选择表格的DOM引用
const selectedProducts = ref([]);    // 在产品模态框中临时选中的产品
const selectedTable = ref(null);     // 已选产品表格的DOM引用
const selectedRows = ref([]);        // 在已选产品表格中选中的行
const selectedData = ref([]);        // 最终确认添加到盘点单中的产品列表

// 盘点单统计信息
const total_loss_qty = ref(0)        // 盘亏数量总和
const total_profit_qty = ref(0)      // 盘盈数量总和
const total_loss_price = ref(0)      // 盘亏金额总和
const total_profit_price = ref(0)    // 盘盈金额总和

const isSaved = ref(false); // 是否已保存盘点单

const isSavedPd = ref(false); // 是否已保存盘点单
// 监听产品明细变化
watch(selectedData, (newVal) => {
    total_loss_qty.value = 0
    total_profit_qty.value = 0
    total_loss_price.value = 0
    total_profit_price.value = 0

    newVal.forEach(row => {


        if (isNaN(Number(row.proddti_stockcnt))) {
            ElMessage.warning('盘点数量必须是数字');
            row.proddti_stockcnt = 0;
        }


        //动态监听输入的盘点的数量去判断是盘盈还是盘亏 --大于是盘盈，小于是盘亏
        const stock = Number(row.stock_numder) || 0; // 当前库存
        const cnt = Number(row.proddti_stockcnt) || 0; // 盘点数量

        if (cnt!=0){
            if (cnt > stock) { // 盘盈
                row.proddti_profit = cnt - stock;
                row.proddti_loss = 0;
            } else {           // 盘亏或无盈亏
                row.proddti_loss = stock - cnt;
                row.proddti_profit = 0;
            }
        }else{
          
        }
   

        if (isNaN(Number(row.proddti_loss))) row.proddti_loss = 0;
        if (isNaN(Number(row.proddti_profit))) row.proddti_profit = 0;

     
        
        // // 计算盘亏金额
        // const loss_price = (row.proddti_loss || 0) * (row.pro_cost_price || 0);
        // // 计算盘盈金额
        // const profit_price = (row.proddti_profit || 0) * (row.pro_sale_price || 0);

        //计算金额
        total_loss_qty.value += row.proddti_loss;
        total_profit_qty.value += row.proddti_profit;
        total_loss_price.value += row.proddti_loss * row.pro_cost_price;
        total_profit_price.value += row.proddti_profit * row.pro_sale_price;
    });
}, { deep: true });




//添加修正库存按钮
const Reviseinventory = () => {
    if (!isSaved.value) {
        ElMessage.warning('请先保存盘点单，才能修正库存');
        return;
    }

    if (selectedData.value.length === 0) {
        ElMessage.warning('请先添加产品');
        return;
    }

    // 只保留有盘亏的记录
    const paramsList = selectedData.value
        .filter(item => Number(item.proddti_loss) > 0) // 盘亏 > 0
        .map(item => ({
            warehouse_code: qty_order.warehouse_code,
            zone_code: qty_order.zone_code,
            location_code: item.location_code,
            pro_code: item.pro_code,
            stock_numder: Number(item.proddti_stockcnt) // 统一命名
        }));

    if (paramsList.length === 0) {
        ElMessage.warning('没有需要修正的盘亏数据');
        return;
    }

    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要修正的数据');
        return;
    }
    

   

    axios.put('http://localhost:5181/api/Inv_Stock/Update_inv_Stock_numder', paramsList, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then(res => {
        if (res.data > 0) {
            ElMessage.success('库存修正成功');
          
          
        } else {
            ElMessage.error('库存修正失败');
        }
    }).catch(err => {
        console.error(err);
        ElMessage.error('请求失败');
    });
};


// 添加产品    
const productAdd = () => {
    if (!qty_order.warehouse_code) {
        ElMessage.warning('请先选择盘点仓库');
        return;
    }

    if (isSavedPd.value){
        ElMessage.warning('订单已经保存,不可以添加产品');
        return;
    }

    dialogTableVisible.value = true;
    productFill();
    productCount();

};

// 移除选中的产品
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    // 创建一个包含选中项的 stock_entry_no 和 pro_code 的数组
    const selectedEntries = selectedRows.value.map(item => ({
        stock_entry_no: item.stock_entry_no,
        pro_code: item.pro_code
    }));

    // 过滤掉被选中的项
    selectedData.value = selectedData.value.filter(item => {
        // 检查当前项的 stock_entry_no 和 pro_code 是否不在选中的数组中
        return !selectedEntries.some(
            selected =>
                selected.stock_entry_no === item.stock_entry_no &&
                selected.pro_code === item.pro_code
        );
    });

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }
    selectedRows.value = [];
};

// 分页查询产品库存信息
const productFill = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
        params: {
            weahouse_code: qty_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        productData.value = result.data || []
        
    }).catch((err) => {
        console.error(err);
        ElMessage.error('获取产品数据失败');
    });
};

// 查询产品库存总数
const productCount = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
        params: {
            weahouse_code: qty_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        pageCount.value = result.data || 0
    }).catch((err) => {
        console.error(err);
    });
};

//事件触发--仓库变化
const handleSelectChange = (selectedValue) => {
    const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
    qty_order.warehouse_name = selectedItem.warehouse_name;


    //盘点仓库是否冻结
    if (selectedItem.warehouse_freeze === '0') {
        ElMessage.warning('该仓库未冻结');
        qty_order.warehouse_code = "";
        qty_order.warehouse_name = "";
    }


    // 根据选择的仓库编码去给库位赋值
    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
        params: {
            warehouse_code: selectedValue
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warhouse_zone.value = result.data;
    })
};


// 选择入库库区的时触发--事件触发--库区
const handleSzone = (value) => {
    const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
    qty_order.zone_name = selectedItemzone.zone_name;
  
    //获取库位
    getWarehouse_location(value);
}



//入库库位
function getWarehouse_location(value) {

    axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        params: {
            zone_code: value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warehouse_location.value = result.data;
    }).catch((err) => {
        console.info(err)
    })
}

// 结束日期验证
const validateEndDate = (endDate) => {
    if (!qty_order.qty_startdate) {
        ElMessage.warning('请先选择盘点开始日期');
        qty_order.qty_end = null;
        return;
    }
    // 2. 把开始时间和结束时间转换成 Date 对象进行比较
    const start = new Date(qty_order.qty_startdate);
    const end = new Date(endDate);

    if (end < start) {
        ElMessage.error('盘点结束时间必须大于开始时间');
        qty_order.qty_end = null;
    }
};


//选择入库库位的触发事件
const locationEndit = (value, row) => {
    // 1. 直接更新当前行的数据
    row.location_code = value; // 确保location_code更新
    const selectedItem = Warehouse_location.value.find(item => item.location_code === value);
    row.location_name = selectedItem ? selectedItem.location_name : '';

   
};

// 分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    productFill();
};

// 当前页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    productFill();
};

// 查询计量单位
const getMeasure = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "db_measure" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        measureOptios.value = [{ dict_value: "0", dict_label: "请选择单位" }, ...(result.data || [])];
    }).catch((err) => {
        console.error(err);
    });
};

// 根据计量单位id返回计量单位名称
const measureValue = (row) => {
    if (!row) return "无";
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
};

// 查询产品
const productSearch = () => {
    productFill();
    productCount();
};

// 重置产品查询条件
const productReset = () => {
    productcode.value = "";
    dict_code.value = "0";
    productFill();
    productCount();
};

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    selectedData.value = [
        ...selectedData.value,
        ...selectedProducts.value.map(item => ({
            ...item,
            proddti_loss: 0,
            proddti_profit: 0,
            proddti_stockcnt:0,
        }))
    ];

    dialogTableVisible.value = false;
    if (multipleTableRef.value) {
        multipleTableRef.value.clearSelection();
    }
};

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断产品是否可选（防止重复添加）
const isProductSelectable = (row) => {
    return !selectedData.value.some(
        item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
    );
};

// 保存盘点单
const handleAdd = async () => {
    try {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) {
            ElMessage.warning('请先完善必填项');
            return;
        }
        if (selectedData.value.length === 0) {
            ElMessage.warning('请添加盘点产品');
            return;
        }

        // 生成盘点单号
        await obtainCode();

        qty_order.proddti_correct = '1'; // 标记为已修正

        // 保存主表信息
        const mainResponse = await axios.put(
            "http://localhost:5181/api/Inv_Qty/Inv_trf_Insert",
            qty_order,
            { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        

        if (mainResponse.data > 0) {
             // 获取主表ID
             const qtyId = await Select_inv_id();

            // 转换明细数据
            const detailList = selectedData.value.map(item => ({
                qty_id: qtyId,
                pro_name: item.stock_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.stock_model,
                unitmeas_id: String(item.dict_code),
                inventory_numder: item.proddti_stockcnt, 
                proddti_loss: item.proddti_loss,     // 盘亏数量
                proddti_profit: item.proddti_profit, // 盘盈数量
                pro_cost_price: item.pro_cost_price,
                pro_sale_price: item.pro_sale_price,
                location_name: item.location_name, // 库位名称
                location_code: item.location_code, // 库位编码
                proddti_loss_money: (item.proddti_loss * item.pro_cost_price).toFixed(2), // 盘亏金额
                proddti_profit_money: (item.proddti_profit * item.pro_sale_price).toFixed(2), // 盘盈金额
                qty_store: '0',
                stock_entry_no:item.stock_entry_no,
            }));

            // 保存明细
            const  emister=await saveQtyDetails(detailList);

         
            if (emister.data > 0) {
                ElMessage.success('盘点单创建成功');
                isSaved.value = true; // ✅ 设置已保存
                isSavedPd.value = true;
            }



            // // 清空表单
            // Object.assign(qty_order, qtyAdd);
            // selectedData.value = [];

            // 跳回盘点列表
            router.push('/main/Inv/InvQty');
        } else {
            ElMessage.error("主表保存失败");
        }
    } catch (error) {
        console.error("保存出错:", error);
        ElMessage.error("保存过程中发生错误");
    }
};

// 获取新添加的盘点单ID
const Select_inv_id = async () => {
    const response = await axios.get(
        "http://localhost:5181/api/Inv_Qty/inv_Qty_id",
        {
            params: { qty_code: qty_order.qty_code },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }
    );
    return response.data;
};

// 保存盘点明细
const saveQtyDetails = (detailList) => {
    return axios.put(
        "http://localhost:5181/api/Inv_Qty/inv_proddti_Insert",
        detailList,
        { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
    );
};

// 获取盘点单号
const obtainCode = async () => {
    try {
        const result = await axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: { en_code: 16 }, // 盘点单编号规则
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        qty_order.qty_code = result.data;
    } catch (err) {
        console.error("生成单号失败:", err);
        throw err;
    }
};





// 关闭页面
const handleClose = () => {
    Object.assign(qty_order, qtyAdd);
    selectedData.value = [];
    router.push('/main/Inv/InvQty');
};

// 查询盘点类型
const getQtyTypes = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "inv_qty" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        options.value = result.data || [];
    }).catch((err) => {
        console.error(err);
    });
};

// 查询仓库信息
const getWarehouses = () => {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBy_Selectpd", {
        headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    }).then((res) => {
        warehouses.value = res.data || [];
    }).catch((res) => {
        console.log(res);
    });
};

onMounted(() => {
    getQtyTypes();
    getMeasure();
    getWarehouses();
});
</script>

<style scoped>
.inventory-add-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
    min-height: 100vh;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.form-columns {
    display: flex;
    justify-content: space-between;
    gap: 20px;
}

.form-column {
    flex: 1;
}

.product-actions {
    margin-bottom: 15px;
    display: flex;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    
    border-top: none;
    margin-top: -1px;
}

.summary-values {
    display: flex;
    gap: 20px;
    font-weight: bold;
}

.summary-values span {
    padding: 2px 10px;
    border-radius: 4px;
  
  
}

.summary-values span:nth-child(2n) {
  
    color: #f56c6c;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.product-filter {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin: 15px 0;
}

.order-filter {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
}

.order-input :deep(.el-input__inner) {
    cursor: pointer;
    background-color: #f5f7fa;
}

.order-input:hover :deep(.el-input__inner) {
    border-color: #c0c4cc;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}
</style>